package com.zhidisoft.admin.controller;

import java.util.List;
import java.util.UUID;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.zhidisoft.admin.entity.ArticleType;
import com.zhidisoft.admin.service.IArticleTypeService;

@Controller
@RequestMapping("/articleType")
public class ArticleTypeController {

	@Autowired
	private IArticleTypeService typeService;
	@GetMapping("/save")
	public ModelAndView saveUi(){
		List<ArticleType> articleTypes = typeService.geArticleTypes();
		ModelAndView mav = new ModelAndView("articleType/type-save.html");
		mav.addObject("typeList", articleTypes);
		return mav;
	}
	
	@PostMapping("/save")
	public ModelAndView save(@Valid ArticleType articleType,BindingResult result,RedirectAttributes redirectAttributes){
		ModelAndView mav = new ModelAndView("redirect:/articleType/typeList");
		if (result.hasErrors()) {
			mav = new ModelAndView("redirect:/common/err");
			redirectAttributes.addFlashAttribute("errorList", result.getAllErrors());
			return mav;
		}
		articleType.setId(UUID.randomUUID().toString().replace("-", ""));
		typeService.save(articleType);
		return mav;
	}
	
	/**
	 * ModelAndView方法
	 * 文章列表
	 * @return
	 */
	@GetMapping("/typeList")	
	public ModelAndView articleModelAndView(@RequestParam(name="pageNum",defaultValue="1") Integer pageNum,@RequestParam(name="pageSize",defaultValue="5")Integer pageSize){
		ModelAndView mav = new ModelAndView("articleType/type-table.html","list",typeService.findPage(pageNum, pageSize));
		mav.addObject("typeList", typeService.geArticleTypes());
		return mav;	
	}
}
